#!/bin/bash
# 将要删除的文件移动到垃圾桶，防止误删文件
TRASH_CAN="$HOME/trashcan"

# 校验文件存放路径
checkTrashCan() {
    if [ ! -d $TRASH_CAN ] 
    then
        mkdir -p $TRASH_CAN
    fi
    if [ ! -d $TRASH_CAN ] 
    then
        return 0
    else
        return 1
    fi
}

# 记录操作日志
recordOperateLog() {
    logFilePath="$TRASH_CAN/trashcanlog$(date "+%y%m%d").log"
    if [ ! -f $logFilePath ] 
    then
        touch $logFilePath
    fi
    message="$(date "+%Y-%m-%d %T") : $1"
    echo $message >> $logFilePath
}

# 执行主程序
if [ $# -lt 1 ] 
then
    echo "usage:trash.sh [filename] [dirname]"
    exit 1
fi
# 校验存放目录
checkTrashCan
checked=$?
if test $[checked] -ne 1
then
    echo "error:$TRASH_CAN not exist and can not create folder $TRASH_CAN"
    exit 1
fi
echo "move items to $TRASH_CAN"
# 执行移动 
for arg in $*
do
    newname="$TRASH_CAN/$(date "+%y%m%d_%H%M%S")_$(basename "$arg")"
    action="none operation"
    # 处理相对路径的文件或者文件夹
    reg="^/.*"
    if [[ "$arg" =~ $reg ]]
    then   
    	absolutePath="$arg"
    else
        currentPath="$(pwd)"
        reg="^\./.*"
       	if [[ "$arg" =~ $reg ]]
        then
            absolutePath="$currentPath/${arg:2}"
        else
            absolutePath="$currentPath/$arg"
        fi
    fi
    if [ -f "$arg" ]
    then
        mv "$arg" "$newname"
        action="move file $absolutePath to $newname"
    elif [ -d "$arg" ]
    then
        mv "$arg" "$newname"
        action="move dir $absolutePath to $newname"
    fi
    echo "$action"
    recordOperateLog "$action"
done
echo "work done"

